/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.gianluca.lotteria.gui;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.swing.JOptionPane;
import org.gianluca.lotteria.entities.Biglietti;
import org.gianluca.lotteria.entities.BigliettiJpaController;
import org.gianluca.lotteria.entities.Blocchetti;
import org.gianluca.lotteria.entities.BlocchettiJpaController;
import org.gianluca.lotteria.entities.Persone;
import org.gianluca.lotteria.entities.PersoneJpaController;
import org.gianluca.lotteria.entities.exceptions.IllegalOrphanException;
import org.gianluca.lotteria.entities.exceptions.NonexistentEntityException;

/**
 *
 * @author gianluca
 */
public class Main extends javax.swing.JFrame {

    private EntityManagerFactory emf;
    private BigliettiJpaController controllerBiglietti;
    private BlocchettiJpaController controllerBlocchetti;
    private PersoneJpaController controllerPersone;

    /**
     * Creates new form NewApplication
     */
    public Main() {
        initComponents();
        emf = javax.persistence.Persistence.createEntityManagerFactory(("org.gianluca_lotteria_jar_1.0-SNAPSHOTPU"));
        controllerBiglietti = new BigliettiJpaController(emf);
        controllerBlocchetti = new BlocchettiJpaController(emf);
        controllerPersone = new PersoneJpaController(emf);

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        entityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("org.gianluca_lotteria_jar_1.0-SNAPSHOTPU").createEntityManager();
        personeQuery = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT p FROM Persone p");
        personeList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(personeQuery.getResultList());
        blocchettiQuery = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT b FROM Blocchetti b");
        blocchettiList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(blocchettiQuery.getResultList());
        bigliettiQuery = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT b FROM Biglietti b");
        bigliettiList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(bigliettiQuery.getResultList());
        bigliettiVenduti = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT COUNT(b.venduto) FROM Biglietti b WHERE b.venduto=1");
        bigliettiTotali = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT COUNT(b) FROM Biglietti b");
        mainPanel = new javax.swing.JPanel();
        jTabbedPane = new javax.swing.JTabbedPane();
        jPanelInserimento = new javax.swing.JPanel();
        panelInserimentoBlocchetto = new javax.swing.JPanel();
        lblBigliettoIniziale = new javax.swing.JLabel();
        lblNumeroBiglietti = new javax.swing.JLabel();
        txtBigliettoIniziale = new javax.swing.JTextField();
        txtNumeroBiglietti = new javax.swing.JTextField();
        lblPersonaRiferimento = new javax.swing.JLabel();
        txtPersonaRiferimento = new javax.swing.JTextField();
        scrlPanPersone = new javax.swing.JScrollPane();
        tblPersone = new javax.swing.JTable(){
            public boolean isCellEditable(int rowIndex, int colIndex) {
                return false;   //Disallow the editing of any cell
            }
        }
        ;
        btnSaveBlocchetti = new javax.swing.JButton();
        panelInserimentoPersone = new javax.swing.JPanel();
        lblNome = new javax.swing.JLabel();
        lblCognome = new javax.swing.JLabel();
        txtNome = new javax.swing.JTextField();
        txtCognome = new javax.swing.JTextField();
        btnSavePersone = new javax.swing.JButton();
        jPanelRicerca = new javax.swing.JPanel();
        panelBlocchetto = new javax.swing.JPanel();
        lblBigliettoIniziale1 = new javax.swing.JLabel();
        lblNumeroBiglietti1 = new javax.swing.JLabel();
        txtBigliettoIniziale1 = new javax.swing.JTextField();
        txtNumeroBiglietti1 = new javax.swing.JTextField();
        lblPersonaRiferimento1 = new javax.swing.JLabel();
        txtPersonaRiferimento1 = new javax.swing.JTextField();
        scrlPanPersone1 = new javax.swing.JScrollPane();
        jTableBlocchetti = new javax.swing.JTable(){
            public boolean isCellEditable(int rowIndex, int colIndex) {
                return false;   //Disallow the editing of any cell
            }
        }
        ;
        btnRicercaBlocchetti = new javax.swing.JButton();
        btnCancella = new javax.swing.JButton();
        lblBiglietto = new javax.swing.JLabel();
        txtBiglietto = new javax.swing.JTextField();
        jPanelBiglietti = new javax.swing.JPanel();
        lblBigliettoIniziale2 = new javax.swing.JLabel();
        lblBigliettoFinale = new javax.swing.JLabel();
        txtBigliettoIniziale2 = new javax.swing.JTextField();
        txtBigliettoFinale = new javax.swing.JTextField();
        scrlPanPersone2 = new javax.swing.JScrollPane();
        jTableBiglietti = new javax.swing.JTable(){
            public boolean isCellEditable(int rowIndex, int colIndex) {
                return false;   //Disallow the editing of any cell
            }
        }
        ;
        btnMostraBiglietti = new javax.swing.JButton();
        btnVenduti = new javax.swing.JButton();
        btnInvenduti = new javax.swing.JButton();
        lblBigliettiVenduti = new javax.swing.JLabel();
        lblBigliettiTotali = new javax.swing.JLabel();
        menuBar = new javax.swing.JMenuBar();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Lotteria Parrocchia \"Gesù Risorto\"");
        setResizable(false);

        jTabbedPane.setName(""); // NOI18N

        jPanelInserimento.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jPanelInserimentoMouseClicked(evt);
            }
        });

        panelInserimentoBlocchetto.setBorder(javax.swing.BorderFactory.createTitledBorder("Inserimento Blocchetto"));
        panelInserimentoBlocchetto.setName(""); // NOI18N
        panelInserimentoBlocchetto.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                panelInserimentoBlocchettoFocusGained(evt);
            }
        });

        lblBigliettoIniziale.setText("Biglietto iniziale:");

        lblNumeroBiglietti.setText("Numero di biglietti:");

        lblPersonaRiferimento.setText("Persona di riferimento:");

        txtPersonaRiferimento.setEditable(false);

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, tblPersone, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.cognome} ${selectedElement.nome}"), txtPersonaRiferimento, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        txtPersonaRiferimento.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtPersonaRiferimentoActionPerformed(evt);
            }
        });

        scrlPanPersone.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        tblPersone.setAutoCreateRowSorter(true);
        tblPersone.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        tblPersone.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_ALL_COLUMNS);
        tblPersone.setEditingColumn(0);
        tblPersone.setEditingRow(0);
        tblPersone.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, personeList, tblPersone, "persone");
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${cognome}"));
        columnBinding.setColumnName("Cognome");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${nome}"));
        columnBinding.setColumnName("Nome");
        columnBinding.setColumnClass(String.class);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        scrlPanPersone.setViewportView(tblPersone);

        btnSaveBlocchetti.setText("Salva");
        btnSaveBlocchetti.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaveBlocchettiActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout panelInserimentoBlocchettoLayout = new org.jdesktop.layout.GroupLayout(panelInserimentoBlocchetto);
        panelInserimentoBlocchetto.setLayout(panelInserimentoBlocchettoLayout);
        panelInserimentoBlocchettoLayout.setHorizontalGroup(
            panelInserimentoBlocchettoLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(panelInserimentoBlocchettoLayout.createSequentialGroup()
                .addContainerGap()
                .add(panelInserimentoBlocchettoLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(scrlPanPersone, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                    .add(panelInserimentoBlocchettoLayout.createSequentialGroup()
                        .add(panelInserimentoBlocchettoLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(lblPersonaRiferimento)
                            .add(lblNumeroBiglietti)
                            .add(lblBigliettoIniziale))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(panelInserimentoBlocchettoLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(txtBigliettoIniziale, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 173, Short.MAX_VALUE)
                            .add(txtNumeroBiglietti)
                            .add(txtPersonaRiferimento)))
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, panelInserimentoBlocchettoLayout.createSequentialGroup()
                        .add(0, 0, Short.MAX_VALUE)
                        .add(btnSaveBlocchetti, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 67, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        panelInserimentoBlocchettoLayout.setVerticalGroup(
            panelInserimentoBlocchettoLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(panelInserimentoBlocchettoLayout.createSequentialGroup()
                .add(26, 26, 26)
                .add(panelInserimentoBlocchettoLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(lblBigliettoIniziale)
                    .add(txtBigliettoIniziale, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(panelInserimentoBlocchettoLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(lblNumeroBiglietti)
                    .add(txtNumeroBiglietti, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(panelInserimentoBlocchettoLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(lblPersonaRiferimento)
                    .add(txtPersonaRiferimento, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(18, 18, 18)
                .add(scrlPanPersone, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 167, Short.MAX_VALUE)
                .add(18, 18, 18)
                .add(btnSaveBlocchetti)
                .addContainerGap())
        );

        getRootPane().setDefaultButton(btnSaveBlocchetti);

        panelInserimentoPersone.setBorder(javax.swing.BorderFactory.createTitledBorder("Inserimento Persone"));
        panelInserimentoPersone.setName(""); // NOI18N

        lblNome.setText("Nome:");

        lblCognome.setText("Cognome:");

        btnSavePersone.setText("Salva");
        btnSavePersone.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSavePersoneActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout panelInserimentoPersoneLayout = new org.jdesktop.layout.GroupLayout(panelInserimentoPersone);
        panelInserimentoPersone.setLayout(panelInserimentoPersoneLayout);
        panelInserimentoPersoneLayout.setHorizontalGroup(
            panelInserimentoPersoneLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(panelInserimentoPersoneLayout.createSequentialGroup()
                .addContainerGap()
                .add(panelInserimentoPersoneLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(panelInserimentoPersoneLayout.createSequentialGroup()
                        .add(panelInserimentoPersoneLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(lblCognome)
                            .add(lblNome))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                        .add(panelInserimentoPersoneLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(txtCognome)
                            .add(txtNome)))
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, panelInserimentoPersoneLayout.createSequentialGroup()
                        .add(0, 218, Short.MAX_VALUE)
                        .add(btnSavePersone, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 67, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        panelInserimentoPersoneLayout.setVerticalGroup(
            panelInserimentoPersoneLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(panelInserimentoPersoneLayout.createSequentialGroup()
                .add(26, 26, 26)
                .add(panelInserimentoPersoneLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(lblNome)
                    .add(txtNome, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(panelInserimentoPersoneLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(lblCognome)
                    .add(txtCognome, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(18, 18, 18)
                .add(btnSavePersone)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        getRootPane().setDefaultButton(btnSaveBlocchetti);

        org.jdesktop.layout.GroupLayout jPanelInserimentoLayout = new org.jdesktop.layout.GroupLayout(jPanelInserimento);
        jPanelInserimento.setLayout(jPanelInserimentoLayout);
        jPanelInserimentoLayout.setHorizontalGroup(
            jPanelInserimentoLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanelInserimentoLayout.createSequentialGroup()
                .addContainerGap()
                .add(panelInserimentoBlocchetto, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 26, Short.MAX_VALUE)
                .add(panelInserimentoPersone, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanelInserimentoLayout.setVerticalGroup(
            jPanelInserimentoLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanelInserimentoLayout.createSequentialGroup()
                .addContainerGap()
                .add(jPanelInserimentoLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jPanelInserimentoLayout.createSequentialGroup()
                        .add(panelInserimentoPersone, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(0, 0, Short.MAX_VALUE))
                    .add(panelInserimentoBlocchetto, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

        jTabbedPane.addTab("Inserimento", jPanelInserimento);

        panelBlocchetto.setBorder(javax.swing.BorderFactory.createTitledBorder("Blocchetto"));
        panelBlocchetto.setName(""); // NOI18N
        panelBlocchetto.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                panelBlocchettoFocusGained(evt);
            }
        });

        lblBigliettoIniziale1.setText("Biglietto iniziale:");

        lblNumeroBiglietti1.setText("Numero di biglietti:");

        txtBigliettoIniziale1.setEditable(false);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, jTableBlocchetti, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.numeroIniziale}"), txtBigliettoIniziale1, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        txtNumeroBiglietti1.setEditable(false);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, jTableBlocchetti, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.numerofinale-selectedElement.numeroIniziale+1}"), txtNumeroBiglietti1, org.jdesktop.beansbinding.BeanProperty.create("text"), "");
        bindingGroup.addBinding(binding);

        lblPersonaRiferimento1.setText("Persona di riferimento:");

        txtPersonaRiferimento1.setEditable(false);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, jTableBlocchetti, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.IDPersona.cognome} ${selectedElement.IDPersona.nome}"), txtPersonaRiferimento1, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        txtPersonaRiferimento1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtPersonaRiferimento1ActionPerformed(evt);
            }
        });

        scrlPanPersone1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        jTableBlocchetti.setAutoCreateRowSorter(true);
        jTableBlocchetti.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        jTableBlocchetti.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_ALL_COLUMNS);
        jTableBlocchetti.setEditingColumn(0);
        jTableBlocchetti.setEditingRow(0);
        jTableBlocchetti.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);

        jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, blocchettiList, jTableBlocchetti);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${numeroIniziale}"));
        columnBinding.setColumnName("Numero Iniziale");
        columnBinding.setColumnClass(Integer.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${numerofinale}"));
        columnBinding.setColumnName("Numerofinale");
        columnBinding.setColumnClass(Integer.class);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        scrlPanPersone1.setViewportView(jTableBlocchetti);

        btnRicercaBlocchetti.setText("Ricerca");
        btnRicercaBlocchetti.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRicercaBlocchettiActionPerformed(evt);
            }
        });

        btnCancella.setText("Cancella");
        btnCancella.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancellaActionPerformed(evt);
            }
        });

        lblBiglietto.setText("Biglietto:");

        org.jdesktop.layout.GroupLayout panelBlocchettoLayout = new org.jdesktop.layout.GroupLayout(panelBlocchetto);
        panelBlocchetto.setLayout(panelBlocchettoLayout);
        panelBlocchettoLayout.setHorizontalGroup(
            panelBlocchettoLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(panelBlocchettoLayout.createSequentialGroup()
                .addContainerGap()
                .add(panelBlocchettoLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(scrlPanPersone1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                    .add(panelBlocchettoLayout.createSequentialGroup()
                        .add(lblBigliettoIniziale1)
                        .add(37, 37, 37)
                        .add(txtBigliettoIniziale1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 204, Short.MAX_VALUE))
                    .add(panelBlocchettoLayout.createSequentialGroup()
                        .add(lblNumeroBiglietti1)
                        .add(24, 24, 24)
                        .add(txtNumeroBiglietti1))
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, panelBlocchettoLayout.createSequentialGroup()
                        .add(0, 0, Short.MAX_VALUE)
                        .add(btnCancella))
                    .add(panelBlocchettoLayout.createSequentialGroup()
                        .add(panelBlocchettoLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(lblPersonaRiferimento1)
                            .add(lblBiglietto))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(panelBlocchettoLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(panelBlocchettoLayout.createSequentialGroup()
                                .add(txtBiglietto)
                                .add(18, 18, 18)
                                .add(btnRicercaBlocchetti, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 90, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                            .add(txtPersonaRiferimento1))))
                .addContainerGap())
        );
        panelBlocchettoLayout.setVerticalGroup(
            panelBlocchettoLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(panelBlocchettoLayout.createSequentialGroup()
                .addContainerGap()
                .add(panelBlocchettoLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(lblBigliettoIniziale1)
                    .add(txtBigliettoIniziale1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(panelBlocchettoLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(lblNumeroBiglietti1)
                    .add(txtNumeroBiglietti1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(panelBlocchettoLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(lblPersonaRiferimento1)
                    .add(txtPersonaRiferimento1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(18, 18, 18)
                .add(panelBlocchettoLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(btnRicercaBlocchetti)
                    .add(lblBiglietto)
                    .add(txtBiglietto, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 21, Short.MAX_VALUE)
                .add(scrlPanPersone1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 133, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(16, 16, 16)
                .add(btnCancella))
        );

        getRootPane().setDefaultButton(btnSaveBlocchetti);

        jPanelBiglietti.setBorder(javax.swing.BorderFactory.createTitledBorder("Biglietto"));

        lblBigliettoIniziale2.setText("Biglietto iniziale:");

        lblBigliettoFinale.setText("Biglietto finale:");

        scrlPanPersone2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        jTableBiglietti.setAutoCreateRowSorter(true);
        jTableBiglietti.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        jTableBiglietti.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_ALL_COLUMNS);
        jTableBiglietti.setEditingColumn(0);
        jTableBiglietti.setEditingRow(0);
        jTableBiglietti.setSelectionMode(javax.swing.ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

        jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, bigliettiList, jTableBiglietti, "biglietti");
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${numero}"));
        columnBinding.setColumnName("Numero");
        columnBinding.setColumnClass(Integer.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${venduto}"));
        columnBinding.setColumnName("Venduto");
        columnBinding.setColumnClass(Boolean.class);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        scrlPanPersone2.setViewportView(jTableBiglietti);

        btnMostraBiglietti.setText("Mostra");
        btnMostraBiglietti.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnMostraBigliettiActionPerformed(evt);
            }
        });

        btnVenduti.setText("Venduti");
        btnVenduti.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnVendutiActionPerformed(evt);
            }
        });

        btnInvenduti.setText("Invenduti");
        btnInvenduti.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnInvendutiActionPerformed(evt);
            }
        });

        lblBigliettiVenduti.setForeground(new java.awt.Color(0, 0, 204));
        lblBigliettiVenduti.setText("Biglietti venduti:" + bigliettiVenduti.getSingleResult().toString());

        lblBigliettiTotali.setForeground(new java.awt.Color(255, 0, 0));
        lblBigliettiTotali.setText("Biglietti totali:" + bigliettiTotali.getSingleResult().toString());

        org.jdesktop.layout.GroupLayout jPanelBigliettiLayout = new org.jdesktop.layout.GroupLayout(jPanelBiglietti);
        jPanelBiglietti.setLayout(jPanelBigliettiLayout);
        jPanelBigliettiLayout.setHorizontalGroup(
            jPanelBigliettiLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanelBigliettiLayout.createSequentialGroup()
                .addContainerGap()
                .add(jPanelBigliettiLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(scrlPanPersone2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                    .add(jPanelBigliettiLayout.createSequentialGroup()
                        .add(lblBigliettoIniziale2)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(txtBigliettoIniziale2))
                    .add(jPanelBigliettiLayout.createSequentialGroup()
                        .add(lblBigliettoFinale)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                        .add(txtBigliettoFinale))
                    .add(jPanelBigliettiLayout.createSequentialGroup()
                        .add(0, 0, Short.MAX_VALUE)
                        .add(btnMostraBiglietti))
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanelBigliettiLayout.createSequentialGroup()
                        .add(jPanelBigliettiLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                            .add(btnVenduti, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 116, Short.MAX_VALUE)
                            .add(lblBigliettiVenduti, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 30, Short.MAX_VALUE)
                        .add(jPanelBigliettiLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                            .add(btnInvenduti, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 116, Short.MAX_VALUE)
                            .add(lblBigliettiTotali, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .addContainerGap())
        );
        jPanelBigliettiLayout.setVerticalGroup(
            jPanelBigliettiLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanelBigliettiLayout.createSequentialGroup()
                .addContainerGap()
                .add(jPanelBigliettiLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(lblBigliettoIniziale2)
                    .add(txtBigliettoIniziale2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(18, 18, 18)
                .add(jPanelBigliettiLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(lblBigliettoFinale)
                    .add(txtBigliettoFinale, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(btnMostraBiglietti)
                .add(18, 18, 18)
                .add(scrlPanPersone2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 134, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jPanelBigliettiLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(btnVenduti)
                    .add(btnInvenduti))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jPanelBigliettiLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(lblBigliettiVenduti, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 23, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(lblBigliettiTotali, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 23, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        getRootPane().setDefaultButton(btnSaveBlocchetti);
        getRootPane().setDefaultButton(btnSaveBlocchetti);

        org.jdesktop.layout.GroupLayout jPanelRicercaLayout = new org.jdesktop.layout.GroupLayout(jPanelRicerca);
        jPanelRicerca.setLayout(jPanelRicercaLayout);
        jPanelRicercaLayout.setHorizontalGroup(
            jPanelRicercaLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanelRicercaLayout.createSequentialGroup()
                .addContainerGap()
                .add(panelBlocchetto, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(18, 18, 18)
                .add(jPanelBiglietti, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanelRicercaLayout.setVerticalGroup(
            jPanelRicercaLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanelRicercaLayout.createSequentialGroup()
                .addContainerGap()
                .add(jPanelRicercaLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                    .add(jPanelBiglietti, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 350, Short.MAX_VALUE)
                    .add(panelBlocchetto, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(29, Short.MAX_VALUE))
        );

        jTabbedPane.addTab("Ricerca Modifica e Cancellazione", jPanelRicerca);

        org.jdesktop.layout.GroupLayout mainPanelLayout = new org.jdesktop.layout.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 706, Short.MAX_VALUE)
            .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(mainPanelLayout.createSequentialGroup()
                    .addContainerGap()
                    .add(jTabbedPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 686, Short.MAX_VALUE)
                    .addContainerGap()))
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 440, Short.MAX_VALUE)
            .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(mainPanelLayout.createSequentialGroup()
                    .addContainerGap()
                    .add(jTabbedPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 418, Short.MAX_VALUE)
                    .addContainerGap()))
        );

        jTabbedPane.getAccessibleContext().setAccessibleName("Blocchetti");

        setJMenuBar(menuBar);

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .add(mainPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .add(mainPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jPanelInserimentoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanelInserimentoMouseClicked
        tblPersone.repaint();
    }//GEN-LAST:event_jPanelInserimentoMouseClicked

    private void btnSavePersoneActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSavePersoneActionPerformed
        if (checkPersoneParameters()) {
            Persone persona = new Persone();
            persona.setCognome(txtCognome.getText());
            persona.setNome(txtNome.getText());

            controllerPersone.create(persona);

            //personeList.clear();
            //personList is observable
            personeList.add(persona);

            txtNome.setText("");
            txtCognome.setText("");
        }
    }//GEN-LAST:event_btnSavePersoneActionPerformed

    private void panelInserimentoBlocchettoFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_panelInserimentoBlocchettoFocusGained

    }//GEN-LAST:event_panelInserimentoBlocchettoFocusGained

    private void btnSaveBlocchettiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveBlocchettiActionPerformed

        if (checkBlocchettoParameters()) {
            
            int selectedRow = tblPersone.getSelectedRow();
            int effectiveRow = tblPersone.convertRowIndexToModel(selectedRow);
            
            Persone personaSelezionata = personeList.get(effectiveRow);
            
            Blocchetti blocchetto = new Blocchetti();
            blocchetto.setIDPersona(personaSelezionata);
            blocchetto.setNumeroIniziale(Integer.parseInt(txtBigliettoIniziale.getText()));
            blocchetto.setNumerofinale(blocchetto.getNumeroIniziale() + Integer.parseInt(txtNumeroBiglietti.getText()) - 1);

            controllerBlocchetti.create(blocchetto);
            blocchettiList.add(blocchetto);

            try {

                //entityManager.getTransaction().begin();
                //entityManager.persist(blocchetto);
                for (int i = blocchetto.getNumeroIniziale(); i <= blocchetto.getNumerofinale(); i++) {
                    Biglietti biglietto = new Biglietti();
                    biglietto.setNumero(i);
                    biglietto.setIDBlocchetto(blocchetto);
                    biglietto.setVenduto(false);
                    controllerBiglietti.create(biglietto);

                    bigliettiList.add(biglietto);
                    //entityManager.persist(biglietto);
                }
                
                lblBigliettiTotali.setText("Biglietti totali: " + bigliettiTotali.getSingleResult().toString());

            } catch (Exception e) {
                JOptionPane.showMessageDialog(panelInserimentoBlocchetto, "Errore nell'inserimento, riprovare.\n" + e.getMessage());
            }
            
        }
    }//GEN-LAST:event_btnSaveBlocchettiActionPerformed

    private void txtPersonaRiferimentoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtPersonaRiferimentoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtPersonaRiferimentoActionPerformed

    private void txtPersonaRiferimento1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtPersonaRiferimento1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtPersonaRiferimento1ActionPerformed

    private void btnRicercaBlocchettiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRicercaBlocchettiActionPerformed
        
      if (txtBiglietto.getText().matches("\\d+")) {
          
          Blocchetti blocchetto;
          blocchetto = (Blocchetti) emf.createEntityManager().createNamedQuery("Blocchetti.findByNumero").setParameter("numero", Integer.parseInt(txtBiglietto.getText())).getSingleResult();
          
         
               
          if (blocchetto != null ) {
              txtBigliettoIniziale1.setText(Integer.toString(blocchetto.getNumeroIniziale()));
              int numeroBiglietti = blocchetto.getNumerofinale()-blocchetto.getNumeroIniziale()+1;
              txtNumeroBiglietti1.setText(Integer.toString(numeroBiglietti));
              
              Persone persona = blocchetto.getIDPersona();
              txtPersonaRiferimento1.setText(persona.getCognome() + " " + persona.getNome());
              
              txtBigliettoIniziale2.setText(txtBiglietto.getText());
              this.btnMostraBigliettiActionPerformed(evt);
          }
          
      }
    }//GEN-LAST:event_btnRicercaBlocchettiActionPerformed

    private void panelBlocchettoFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_panelBlocchettoFocusGained
        // TODO add your handling code here:
    }//GEN-LAST:event_panelBlocchettoFocusGained

    private void btnMostraBigliettiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnMostraBigliettiActionPerformed
        // TODO add your handling code here:
        int bigliettoIniziale = Integer.MIN_VALUE;
        int bigliettoFinale = Integer.MAX_VALUE;
        if (txtBigliettoIniziale2.getText().matches("\\d+")) {
            bigliettoIniziale = Integer.parseInt(txtBigliettoIniziale2.getText());
        }
        if (txtBigliettoFinale.getText().matches("\\d+")) {
            bigliettoFinale = Integer.parseInt(txtBigliettoFinale.getText());
        }
        
        Query query = emf.createEntityManager().createNamedQuery("Biglietti.findByNumeri");
        query.setParameter("numeroIniziale", bigliettoIniziale);
        query.setParameter("numeroFinale",bigliettoFinale);
        
        bigliettiList.clear();
        bigliettiList.addAll(query.getResultList());
        jTableBiglietti.getSelectionModel().setSelectionInterval(0, 0);
    }//GEN-LAST:event_btnMostraBigliettiActionPerformed

    private void btnVendutiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnVendutiActionPerformed
        int[] bigliettiSelezionatiOrdine = jTableBiglietti.getSelectedRows();
        int[] bigliettiSelezionati = new int[bigliettiSelezionatiOrdine.length];
        
        for (int i=0;i<bigliettiSelezionatiOrdine.length;i++)
            bigliettiSelezionati[i]=jTableBiglietti.convertRowIndexToModel(bigliettiSelezionatiOrdine[i]);
        
        for (int i : bigliettiSelezionati)
        {
            Integer numero = (Integer) jTableBiglietti.getModel().getValueAt(i, 0);
            Biglietti biglietto = controllerBiglietti.findBiglietti(numero);
            if (!biglietto.getVenduto()) {
                biglietto.setVenduto(true);
                try {
                    controllerBiglietti.edit(biglietto);
                    bigliettiList.set(i, biglietto);
                } catch (NonexistentEntityException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                } catch (Exception ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            
        }
        
        lblBigliettiVenduti.setText("Biglietti venduti:" + bigliettiVenduti.getSingleResult().toString());

    }//GEN-LAST:event_btnVendutiActionPerformed

    private void btnInvendutiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnInvendutiActionPerformed
        int[] bigliettiSelezionatiOrdine = jTableBiglietti.getSelectedRows();
        int[] bigliettiSelezionati = new int[bigliettiSelezionatiOrdine.length];
        
        for (int i=0;i<bigliettiSelezionatiOrdine.length;i++)
            bigliettiSelezionati[i]=jTableBiglietti.convertRowIndexToModel(bigliettiSelezionatiOrdine[i]);
        
        
        for (int i : bigliettiSelezionati)
        {
            Integer numero = (Integer) jTableBiglietti.getModel().getValueAt(i, 0);
            Biglietti biglietto = controllerBiglietti.findBiglietti(numero);
            if (biglietto.getVenduto()) {
                biglietto.setVenduto(false);
                try {
                    controllerBiglietti.edit(biglietto);
                    bigliettiList.set(i, biglietto);
                } catch (NonexistentEntityException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                } catch (Exception ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            
        }
        
        lblBigliettiVenduti.setText("Biglietti venduti:" + bigliettiVenduti.getSingleResult().toString());

    }//GEN-LAST:event_btnInvendutiActionPerformed

    private void btnCancellaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancellaActionPerformed
        
        int selectedBlocchetto = jTableBlocchetti.convertRowIndexToModel(jTableBlocchetti.getSelectedRow());
        
        if (selectedBlocchetto != -1) {
            Integer bigliettoIniziale = (Integer) jTableBlocchetti.getModel().getValueAt(selectedBlocchetto, 0);
            
            Blocchetti blocchetto;
            blocchetto = (Blocchetti) emf.createEntityManager().createNamedQuery("Blocchetti.findByNumeroIniziale").setParameter("numeroIniziale", bigliettoIniziale).getSingleResult();
          
            /*for (int i=blocchetto.getNumeroIniziale(); i<=blocchetto.getNumerofinale();i++) {
                try {
                    Biglietti biglietto = controllerBiglietti.findBiglietti(new Integer(i));
                    
                    if (biglietto != null ) {
                        controllerBiglietti.destroy(new Integer(i));

                        bigliettiList.remove(biglietto);
                    }
                } catch (NonexistentEntityException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
                
            }*/
            try {
                controllerBlocchetti.destroy(blocchetto.getId());
            } catch (IllegalOrphanException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            } catch (NonexistentEntityException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }
            blocchettiList.remove(blocchetto);
            bigliettiList.clear();
            bigliettiList.addAll(controllerBiglietti.findBigliettiEntities());
            lblBigliettiTotali.setText("Biglietti totali: " + bigliettiTotali.getSingleResult().toString());
        }
    }//GEN-LAST:event_btnCancellaActionPerformed

    private boolean checkBlocchettoParameters() {

        StringBuffer message = new StringBuffer();

        if (txtBigliettoIniziale.getText().isEmpty()) {
            message.append("Inserire un valore per il campo ");
            message.append("'");
            message.append(lblBigliettoIniziale.getText());
            message.append("'");
        } else if (!txtBigliettoIniziale.getText().matches("\\d+")) {
            message.append("Inserire un valore numerico per il campo ");
            message.append("'");
            message.append(lblBigliettoIniziale.getText());
            message.append("'");
        } else if (txtNumeroBiglietti.getText().isEmpty()) {
            message.append("Inserire un valore per il campo ");
            message.append("'");
            message.append(lblNumeroBiglietti.getText());
            message.append("'");
        } else if (!txtNumeroBiglietti.getText().matches("\\d+")) {
            message.append("Inserire un valore numerico per il campo ");
            message.append("'");
            message.append(lblNumeroBiglietti.getText());
            message.append("'");
        } else if (tblPersone.getSelectedRow() == -1) {
            message.append("Prego selezionare una persona di riferimento dalla lista");
        } else {
            int bigliettoIniziale = Integer.parseInt(txtBigliettoIniziale.getText());
            int bigliettoFinale = bigliettoIniziale + Integer.parseInt(txtNumeroBiglietti.getText())-1;
            for (int i = bigliettoIniziale; i<= bigliettoFinale; i++) {

                if (controllerBiglietti.findBiglietti(i) != null) {
                    message.append("Errore nell'inserimento, il biglietto ");
                    message.append("'");
                    message.append(i);
                    message.append("'");
                    message.append(" già esiste.");
                    break;
                }

            }
        }

        if (!message.toString().isEmpty()) {
            JOptionPane.showMessageDialog(this, message.toString());
        }

        return (message.toString().isEmpty());
    }

    private boolean checkPersoneParameters() {

        StringBuffer message = new StringBuffer();

        if (txtNome.getText().isEmpty()) {
            message.append("Inserire un valore per il campo ");
            message.append("'");
            message.append(lblNome.getText());
            message.append("'");
        } else if (txtCognome.getText().isEmpty()) {
            message.append("Inserire un valore per il campo ");
            message.append("'");
            message.append(lblCognome.getText());
            message.append("'");
        }

        if (!message.toString().isEmpty()) {
            JOptionPane.showMessageDialog(this, message.toString());
        }

        return (message.toString().isEmpty());
    }
    
    public String venduto(int i) {
        
        return (i==0?"NO":"SI");
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Main().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private java.util.List<org.gianluca.lotteria.entities.Biglietti> bigliettiList;
    private javax.persistence.Query bigliettiQuery;
    private javax.persistence.Query bigliettiTotali;
    private javax.persistence.Query bigliettiVenduti;
    private java.util.List<org.gianluca.lotteria.entities.Blocchetti> blocchettiList;
    private javax.persistence.Query blocchettiQuery;
    private javax.swing.JButton btnCancella;
    private javax.swing.JButton btnInvenduti;
    private javax.swing.JButton btnMostraBiglietti;
    private javax.swing.JButton btnRicercaBlocchetti;
    private javax.swing.JButton btnSaveBlocchetti;
    private javax.swing.JButton btnSavePersone;
    private javax.swing.JButton btnVenduti;
    private javax.persistence.EntityManager entityManager;
    private javax.swing.JPanel jPanelBiglietti;
    private javax.swing.JPanel jPanelInserimento;
    private javax.swing.JPanel jPanelRicerca;
    private javax.swing.JTabbedPane jTabbedPane;
    private javax.swing.JTable jTableBiglietti;
    private javax.swing.JTable jTableBlocchetti;
    private javax.swing.JLabel lblBigliettiTotali;
    private javax.swing.JLabel lblBigliettiVenduti;
    private javax.swing.JLabel lblBiglietto;
    private javax.swing.JLabel lblBigliettoFinale;
    private javax.swing.JLabel lblBigliettoIniziale;
    private javax.swing.JLabel lblBigliettoIniziale1;
    private javax.swing.JLabel lblBigliettoIniziale2;
    private javax.swing.JLabel lblCognome;
    private javax.swing.JLabel lblNome;
    private javax.swing.JLabel lblNumeroBiglietti;
    private javax.swing.JLabel lblNumeroBiglietti1;
    private javax.swing.JLabel lblPersonaRiferimento;
    private javax.swing.JLabel lblPersonaRiferimento1;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JPanel panelBlocchetto;
    private javax.swing.JPanel panelInserimentoBlocchetto;
    private javax.swing.JPanel panelInserimentoPersone;
    private java.util.List<org.gianluca.lotteria.entities.Persone> personeList;
    private javax.persistence.Query personeQuery;
    private javax.swing.JScrollPane scrlPanPersone;
    private javax.swing.JScrollPane scrlPanPersone1;
    private javax.swing.JScrollPane scrlPanPersone2;
    private javax.swing.JTable tblPersone;
    private javax.swing.JTextField txtBiglietto;
    private javax.swing.JTextField txtBigliettoFinale;
    private javax.swing.JTextField txtBigliettoIniziale;
    private javax.swing.JTextField txtBigliettoIniziale1;
    private javax.swing.JTextField txtBigliettoIniziale2;
    private javax.swing.JTextField txtCognome;
    private javax.swing.JTextField txtNome;
    private javax.swing.JTextField txtNumeroBiglietti;
    private javax.swing.JTextField txtNumeroBiglietti1;
    private javax.swing.JTextField txtPersonaRiferimento;
    private javax.swing.JTextField txtPersonaRiferimento1;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
}
